package com.codemart.lanze.core.freemarker;

import java.io.IOException;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.codemart.lanze.core.freemarker.utils.Freemarker;
import com.codemart.lanze.modules.cms.entity.Channel;
import com.codemart.lanze.modules.cms.entity.Content;
import com.codemart.lanze.modules.cms.service.IChannelService;
import com.codemart.lanze.modules.cms.service.IContentService;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.WrappingTemplateModel;

/**
 * 内容分页指令
 *
 * @author lanze
 */
@Repository
public class DirectiveContentPage implements TemplateDirectiveModel {

	@Autowired
	private IChannelService channelService;
	@Autowired
	private IContentService contentService;

	@SuppressWarnings({ "rawtypes", "unchecked", "deprecation" })
	@Override
	public void execute(Environment env, Map map, TemplateModel[] loopVars, TemplateDirectiveBody body)
			throws TemplateException, IOException {

		QueryWrapper<Content> ew = new QueryWrapper<>();

		/** 文章模型ID */
		Integer model = Freemarker.getInteger(map, "model");
		/** 栏目标识代码 */
		String channelCode = Freemarker.getString(map, "channelCode");
		/** 排序字段 */
		String fields = Freemarker.getString(map, "fields");
		/** 排序顺序 */
		String sort = Freemarker.getString(map, "sort");
		/** 每页显示条数，默认 10 */
		Integer size = Freemarker.getInteger(map, "size");
		size = size == null ? 10 : size;
		int current = Freemarker.getInteger(map, "current");

		Channel channel = new Channel();
		channel.setChannelPath(channelCode);
		channel = channelService.getOne(new QueryWrapper<>(channel));

		ew.eq("channel_id", channel.getId());
		ew.eq("model_id", model);

		if (StringUtils.isNotBlank(fields)) {
			String[] f = StringUtils.split(fields, ",");
			String[] s = StringUtils.split(sort, ",");
			for (int i = 0; i < f.length; i++) {
				if ("asc".equals(s[i])) {
					ew.orderByAsc(f[i]);
				} else {
					ew.orderByDesc(f[i]);
				}
			}
		}

		/** 查询记录总数 */
		Integer total = contentService.count(ew);
		total = total == null ? 0 : total;

		Page<Content> page = new Page<>(current, size);
		IPage<Content> iPage = contentService.page(page, ew);

		/** 查询到的结果 */
		loopVars[0] = WrappingTemplateModel.getDefaultObjectWrapper().wrap(iPage);

		/** 内容的栏目信息 */
		loopVars[1] = WrappingTemplateModel.getDefaultObjectWrapper().wrap(channel);

		/** 当前条件查询记录总数 */
		loopVars[2] = WrappingTemplateModel.getDefaultObjectWrapper().wrap(total);

		body.render(env.getOut());
	}

}
